<template>
    <view class="blurbg">
        <up-navbar title=" " :safeAreaInsetTop="true" bgColor="transparent" :placeholder="true">
			<template #left>
				<view class="flex px-[24rpx] py-[16rpx] border-[1rpx] border-slate-200 rounded-[38rpx]">
					<up-icon name="arrow-left" size="19" @click="goback" color="#000"></up-icon>
					<up-line direction="column" :hairline="false" length="16" margin="0 8px"></up-line>
					<up-icon name="home" size="20" @click="gohome" color="#000"></up-icon>
				</view>
			</template>
		</up-navbar>
        <view>
            <image src="../static/ptbd.png" mode="widthFix" class="w-[100%] block"/>
            <view class="m-[30rpx] mt-[-150rpx] bg-[#fff] rounded-[32rpx] px-[64rpx] pt-[80rpx] pb-[24rpx] relative">
                <view class="tbtitle">绑定信息填写</view>
                <up-form labelPosition="left" :model="Data" :rules="rules" ref="uFormRef">
			        <up-form-item prop="commmunityName" class="mb-[24rpx]" borderBottom>
                        <view >
                            <view class="text-[26rpx] text-[#333] font-bold ">社区</view>
                            <view class=" my-[24rpx] color-[#c1c1c1] text-[26rpx] font-normal" @click="show = !show">{{ Data.commmunityName ? Data.commmunityName : '请选择社区'}}</view>
                        </view>
			        </up-form-item>
                    <up-form-item prop="identity" class="mb-[24rpx]" borderBottom>
                        <view >
                            <view class="text-[26rpx] text-[#333] font-bold ">身份证号</view>
                            <view class="my-[24rpx]">
                                <up-input placeholder="请填写您的身份证号" border="none" maxlength="18" type="idcard" v-model="Data.identity"></up-input>
                            </view>
                         </view>
			        </up-form-item>
                    <up-form-item prop="phone" class="mb-[24rpx]" borderBottom>
                        <view >
                            <view class="text-[26rpx] text-[#333] font-bold ">手机号</view>
                            <view class="my-[24rpx]">
                                <up-input placeholder="请输入您的手机号" border="none" maxlength="11" type="number" v-model="Data.phone" ></up-input>
                            </view>
                        </view>
			        </up-form-item>
                    <up-form-item prop="code" class="mb-[24rpx]" borderBottom>
                        <view >
                            <view class="text-[26rpx] text-[#333] font-bold ">验证码</view>
                            <view class="my-[24rpx] flex justify-between">
                                <view>
                                    <up-input placeholder="请输入您的验证码" border="none" v-model="Data.code" ></up-input>
                                </view>
                                <view v-if="codeTime==0" @click="AuthRegisterCaptcha" class="text-[26rpx] text-[#46A7fd] font-normal">获取验证码</view>
                                <view v-else class="text-[26rpx] text-[#46A7fd] font-normal" >{{codeTime}}</view>
                            </view>
                        </view>
			        </up-form-item>
		        </up-form>
                <view  @click="ApplyBinding" class="mb-[16rpx] text-[28rpx] text-[#fff] font-normal py-[22rpx] rounded-[60rpx] text-center bg-[#46A7FD]">申请绑定</view>
                <view class="flex items-center justify-center">
                    <view class="text-[24rpx] text-[#999] font-normal mr-[16rpx]">更多疑问可向客服咨询</view>
                    <view class="text-[24rpx] text-[#46A7FD] font-normal">联系客服</view>
                </view>
            </view>
        </view>
        <view style="position: relative;">
			<oCode v-show="showCodeValidate" :bg="bg" :slider="slider" @refresh="refreshCode" @close="closeCode" @start="start" @end="end"></oCode>
		</view>
        <up-picker :show="show" :columns="List" keyName="label" @confirm="onConfirm" @cancel="onCancel"></up-picker>
    </view>
</template>

<script setup>
import { ref } from 'vue'
import oCode from '@/components/o-code/o-code.vue'
import { onLoad , onReady } from '@dcloudio/uni-app'
import { GetSlider, sendSMS } from '../../API/login'
import { GetStoreList, SubmitApplication } from '../../API/store'
const { goback , gohome } = useTab()
const { show , List , total , uFormRef , rules , GetList , onConfirm , onCancel , ApplyBinding } = useForm()
const {
    showCodeValidate,
    trackList,
    startSlidingTime,
    requestTime,
    code_id,
    endSlidingTime,
    bg,
    slider,
    codeTime,
    phone,
    isPass,
    Data,
    start,
    end,
    changeCode,
    closeCode,
    refreshCode,
    getGraphicVerificationCode,
    verifyGraphicVerificationCode,
    AuthRegisterCaptcha
} = SlidingBlock()
function useTab (){
    const goback = ()=>{
        uni.navigateBack()
    }
    const gohome = ()=>{
        uni.switchTab({
            url:'/pages/index/index'
        })
    }
    return{
        goback,
        gohome
    }
}
function useForm(){
    const List = ref([])
    const num = ref(0)
    const show = ref(false)
    const uFormRef = ref(null);  
    const rules = ref({
        commmunityName: [{  
            type: 'string',  
            required: true,  
            message: '请选择社区',  
            trigger: ['blur', 'change'],  
        }],  
        name: [{  
            type: 'string',  
            required: true,  
            message: '请填写您的姓名',  
            trigger: ['blur', 'change'],  
        }],
        identity:[{
            type: 'string',  
            required: true,
            message: '请填写您的身份证号',  
            trigger: ['blur', 'change'],
        }],
        phone:[{
			required: true, 
			message: '请输入手机号',
			trigger: ['change','blur'],
		},
		{
			// 自定义验证函数，见上说明
			validator: (rule, value, callback) => {
				// 上面有说，返回true表示校验通过，返回false表示不通过
				// uni.$u.test.mobile()就是返回true或者false的
				return uni.$u.test.mobile(value);
			},
			message: '手机号码不正确',
			// 触发器可以同时用blur和change
			trigger: ['change','blur'],
		}],
        code:[{
            type: 'string',  
            required: true,
            message: '请填写验证码',  
            trigger: ['blur', 'change'],
        }]
    })
    const GetList = async ()=>{
        let { rows , total } = await GetStoreList()
        List.value = [rows.map(item=>{
            return{
                label:item.name,
                id:item.communityId
            }
        })]
        console.log(List.value);
        num.value = total
    }
    const onConfirm = (e)=>{
        Data.value.communityId = e.value[0].id
        Data.value.commmunityName = e.value[0].label
        show.value = false
    }
    const onCancel = ()=>{
        show.value = false
    }
    const ApplyBinding = async ()=>{
        uFormRef.value.validate().then( async(valid) => {  
            if (valid) {
                try {
                    let { data } = await SubmitApplication(Data.value)
                    uni.navigateBack()
                } catch (error) {
                }
            } else {  
                uni.$u.toast('校验失败')
            }  
        }).catch(() => {  
               // 处理验证错误  
               uni.$u.toast('校验失败')
        });     
    }
    return { show , List , num , uFormRef , rules , GetList , onConfirm , onCancel , ApplyBinding }
}
function SlidingBlock (){
    const showCodeValidate = ref(false)
    const trackList = ref([])
    const startSlidingTime = ref(null)
    const requestTime = ref(0)
    const code_id = ref('')
    const endSlidingTime = ref('')
    const bg = ref({
		src: 'http://', // 背景图片路径
		width: 240, // 背景图片大小
		height: 150,
		mode: "aspectFit" // 显示模式
	}) 
	const slider = ref({
		src: "/",
		y: 0,
		width: 40,
		height: 40,
		mode: ''
	})
    const codeTime = ref(0)
    const phone = ref('')
    const isPass = ref(false)
    const Data = ref({
		type: 1,
        communityId:'',
		phone: '',
        code: '',
        // name:'',
        identity:'',
		uuid: "",
        commmunityName:''
    })
    //开始
    const start = (x, y)=>{
		startSlidingTime.value= new Date();
		trackList.value = [];
		trackList.value.push({
			x: x.x,
			y: x.y,
			t: +new Date() - requestTime.value,
			type: 'down'
		})
	}
	//结束
	const end = async (x, y)=>{
		endSlidingTime.value = new Date();
		trackList.value.push({
			type: 'up',
			x: x.x,
			y: x.y,
			t: +new Date() - requestTime.value,
		})
		await verifyGraphicVerificationCode();
		console.log('结束')
	}
	//滑块移动
	const changeCode = (x, y)=>{
		trackList.value.push({
			x,
			y,
			t: +new Date() - requestTime.value,
			type: 'move'
		})
	}
	//关闭弹窗
	const closeCode = ()=>{
		showCodeValidate.value = false;
	}
    // 刷新
	const refreshCode = async(e)=>{
		await getGraphicVerificationCode();
	}
    // 获取图形验证码
    const getGraphicVerificationCode = async()=>{
        try{
            let {data} = await GetSlider()
            requestTime.value = +new Date();
			const {
				backgroundImage,
				backgroundImageWidth,
				backgroundImageHeight,
				templateImage,
				templateImageHeight,
				templateImageWidth
			} = data.captcha;
			bg.value.src = backgroundImage;
			bg.value.width = backgroundImageWidth / 2;
			bg.value.height = backgroundImageHeight / 2;
			slider.value.src = templateImage;
			slider.value.height = templateImageHeight / 2;
			slider.value.width = templateImageWidth / 2;
			code_id.value = data.id;
			phone.value = Data.value.phone;
			isPass.value = false;
			showCodeValidate.value = true;
        }catch(err){
            console.log(err);
        }
    }
    //验证图形验证码
	const verifyGraphicVerificationCode = async()=>{
		const data = {
			captchaTrack: {
			    bgImageHeight: bg.value.height,
			    bgImageWidth: bg.value.width,
			    sliderImageHeight: slider.value.height,
		        sliderImageWidth: slider.value.width,
			    startTime: startSlidingTime.value,
			    stopTime: endSlidingTime.value,
			    trackList: trackList.value,
		    },
			id: code_id.value,
			mobile: phone.value
		}
		let res = null;
        try {
            let res = await sendSMS(JSON.stringify(data))
            Data.value.uuid = res.data
			showCodeValidate.value = false;
			trackList.value = [];
			isPass.value = true;
			codeTime.value = 60
			var timer = setInterval(()=>{
				if (codeTime.value <= 1) {
					clearInterval(timer);
				}
				codeTime.value = codeTime.value - 1
			}, 1000)
        } catch (error) {
            isPass.value = false;
			refreshCode();
        }
	}
    const AuthRegisterCaptcha = async()=>{
		await getGraphicVerificationCode()
    }
    return{ 
        showCodeValidate,
        trackList,
        startSlidingTime,
        requestTime,
        code_id,
        endSlidingTime,
        bg,
        slider,
        codeTime,
        phone,
        isPass,
        Data,
        start,
        end,
        changeCode,
        closeCode,
        refreshCode,
        getGraphicVerificationCode,
        verifyGraphicVerificationCode,
        AuthRegisterCaptcha
    }
}
onLoad( async ()=>{
    await GetList()
})
</script>

<style lang="scss" scoped>
.blurbg{
    min-height: 100vh;
    background: linear-gradient( 180deg, #bcdef8 0%, #F9F9FB 100%);
}
.tbtitle{
    top: 0;
    left: 50%;
    width: 280rpx;
    height: 64rpx;
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    position: absolute;
    text-align: center;
    line-height: 64rpx;
    transform: translate(-50%,-50%);
    border-radius: 32rpx 16rpx 32rpx 16rpx;
    box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(70,167,253,0.5);
    background: linear-gradient( 90deg, #5578F3 0%, #69A7F6 100%);
}
</style>